<?php
/**
 * Created by PhpStorm.
 * User: Sunmer
 * Date: 2019/6/5 0005
 * Time: 15:41
 * Email:Sunmer@foxmail.com
 */
namespace app\api\controller;
use think\Db;
class Cash extends BaseController{
    /**
     * 申请提现
     * @return \think\Response|\think\response\Json|\think\response\Jsonp|\think\response\Redirect|\think\response\View|\think\response\Xml
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function cash()
    {
        $res = request()->param();
        if (empty($res['id'])||empty($res['bank'])||empty($res['money'])){
            return $this->ajax_return('null','参数不完整','201');
        }
        //判断当前用户可提现金额  是否可以提现
        $num = Db::table('tp_user')->where('id',$res['id'])->field('member_ban,member_mobile')->find();
        if ($num['member_ban']<50)
        {
            return $this->ajax_return('null','您当前的可用余额少于50元','201');
        }
        if ($res['money']>$num['member_ban'])
        {
            return $this->ajax_return('null','您当前的可用余额不足','201');
        }
        //查询需要的信息
        $par = Db::table('tp_bank')->where('bank',$res['bank'])->field('bank_uname')->find();
        if (!$par)
        {
            return $this->ajax_return('null','该银行卡不存在','201');
        }
        $result = [
            'cash_id'=>$this->cash_id(10),
            'cash_account'=>$res['bank'],
            'cash_name'=>$par['bank_uname'],
            'cash_mobile'=>$num['member_mobile'],
            'create_at'=>date('Y-m-d H:i:s',time()),
            'cash_way'=>'银行卡',
            'cash_money'=>$res['money'],
        ];
        $para = Db::table('tp_cash')->where('id',$res['id'])->insert($result);
        if ($para){
            // 启动事务
            Db::startTrans();
            try{
                $member_ban = $num['member_ban']-$res['money'];
                $member_diamonds = $num['member_ban']-$res['money'];
                $data = [
                    'member_ban'=>$member_ban,
                    'member_diamonds'=>$member_diamonds,
                ];
                $update = Db::table('tp_user')->where('id',$res['id'])->update($data);
                if ($update)
                {
                    return $this->ajax_return('null','申请提现已提交,请等待管理员审核','200');
                }
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
            }
        }
    }
    /**
     * 提现编号
     * @param int $length
     * @return string
     */
    public function cash_id($length = 10){
        $chars = 'ABCDEFGHIJKLMNOPQRETWVUXYZ0123456789';
        $cash_id = '';
        for ( $i = 0; $i < $length; $i++ )
        {
            $cash_id .=$chars[ mt_rand(0, strlen($chars) - 1) ];
        }
        $cash_id ='TKWZTX'.$cash_id;
        return $cash_id;
    }
}